package com.kitty.syn;

import java.util.*;

public class ResourcePool {

	private ResourceFactory resourceFactory;
	private int maxResources;
	private int currentResources;
	private boolean quit;
	private Set<Object> takeResources = new HashSet<Object>();
	private List<Object> waitResources = new ArrayList<Object>();

	public ResourcePool(ResourceFactory rf, int mr) {
		this.resourceFactory = rf;
		this.maxResources = mr;
	}

	public synchronized Object getResource() throws Exception {
		while (!this.quit) {
			if (!this.waitResources.isEmpty()) {
				Object o = this.waitResources.get(0);

				if (this.resourceFactory.validateResource(o)) {
					o = this.resourceFactory.createResource();
				}
				this.takeResources.add(o);
				this.waitResources.remove(o);
				return o;
			}
			if (this.currentResources < this.maxResources) {
				Object o = this.resourceFactory.createResource();
				this.takeResources.add(o);
				this.currentResources++;
				return o;
			}

			try {
				System.out.println("没有空闲的对象可用,进入等待!");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
		return null;
	}

	public synchronized void returnResource(Object o) {
		if (!this.takeResources.remove(o)) {
			throw new IllegalArgumentException("对象不再池中,无法返回!");
		}
		this.waitResources.add(o);
		this.notify();
	}

	public ResourceFactory getResourceFactory() {
		return resourceFactory;
	}

	public void setResourceFactory(ResourceFactory resourceFactory) {
		this.resourceFactory = resourceFactory;
	}

	public int getMaxResources() {
		return maxResources;
	}

	public void setMaxResources(int maxResources) {
		this.maxResources = maxResources;
	}

	public int getCurrentResources() {
		return currentResources;
	}

	public void setCurrentResources(int currentResources) {
		this.currentResources = currentResources;
	}

	public boolean isQuit() {
		return quit;
	}

	public void setQuit(boolean quit) {
		this.quit = quit;
	}

	public Set<Object> getTakeResources() {
		return takeResources;
	}

	public void setTakeResources(Set<Object> takeResources) {
		this.takeResources = takeResources;
	}

	public List<Object> getWaitResources() {
		return waitResources;
	}

	public void setWaitResources(List<Object> waitResources) {
		this.waitResources = waitResources;
	}

	public synchronized void destory() {
		this.quit = true;
		this.notifyAll();
	}

}
